package com.hankol.newretail

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.ReceiveAddressBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.utils.EmptyViewUtil
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.PopUtils
import com.baselibrary.view.SpacesTopDec
import com.hankol.newretail.adapter.ReceiveAddreessListAdapter
import com.hankol.newretail.databinding.ActivityReceiveAddressBinding
import com.hankol.newretail.viewmodel.AddressAboutViewModel
import com.liaoinstan.springview.utils.DensityUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**新零售-收货地址 选择
 * @author: merbng
 * @time: 2022/8/5 9:48
 * @description:
 */
@Route(path = ActivityRouter.NEW_RETAIL.RECEIVE_ADDRESS)
class ReceiveAddressActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: AddressAboutViewModel
    private lateinit var binding: ActivityReceiveAddressBinding
    private val mAdapter by lazy { ReceiveAddreessListAdapter() }

    // 为空 表示 查看， 不为空 表示 选择地址 需要显示使用中标签
    var id = ""

    companion object {
        const val KEY_ADDRESS_ID = "key_address_id"
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_receive_address
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(AddressAboutViewModel::class.java)
        initView()
        initListener()
        initObserver()
        reqData()
    }

    private fun initView() {
        if (ARouterUtils.parseParams(intent.extras!!, KEY_ADDRESS_ID)[0].checkNotNull()) {
            id = ARouterUtils.parseParams(intent.extras!!, KEY_ADDRESS_ID)[0]
        }
        binding.rvAddressList.adapter = mAdapter
        binding.rvAddressList.addItemDecoration(SpacesTopDec(DensityUtil.dip2px(this, 8f), false))
    }

    //临时存储删除当前选择的地址的id
    var delTempAddressId = 0
    private fun initListener() {
        binding.ivBack.setOnClickListener(this)
        binding.tvAddAddress.setOnClickListener(this)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val receiveAddressBean = adapter.data[position] as ReceiveAddressBean
            if (id.checkNotNull()) {
                //选择地址
                EventBusUtils.sendNotify2Bean(selectAddressMessBus(receiveAddressBean))
                finish()
            }
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val receiveAddressBean = adapter.data[position] as ReceiveAddressBean
            when (view.id) {
                R.id.tv_edit -> {
                    //编辑
                    val bundle = Bundle()
                    bundle.putParcelable(EditOrNewAddAddressActivity.KEY_ADDRESS_BEAN, receiveAddressBean)
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.EDIT_OR_ADD_NEW_ADDRESS, bundle)
                }
                R.id.tv_delete -> {
                    PopUtils.showOkCancelDialog(this, "确认删除地址", object : PopUtils.ICallBack {
                        override fun clickOk() {
                            LoadingManager.showProgress(this@ReceiveAddressActivity, "请稍后...")
                            viewModel.requestDeleteAddress("${receiveAddressBean.id}")
                            if (id == "${receiveAddressBean.id}") {
                                delTempAddressId = receiveAddressBean.id
                            }
                        }

                        override fun clickCancel() {

                        }

                    }, false, "确认", "取消")
                }
                R.id.img_def, R.id.tv_def -> {//设置 默认地址
                    if (receiveAddressBean.def == 0) {
                        LoadingManager.showProgress(this, "请稍后...")
                        viewModel.requestSetDefAddress("${receiveAddressBean.id}")
                    }
                }
            }
        }
    }

    private fun initObserver() {
        viewModel.addressDataLD.observe(this, Observer {
            if (it.checkNotNull()) {
                for (addressBean in it) {
                    if ("${addressBean.id}" == id) {
                        addressBean.useing = true
                    }
                }
            }
            if (it.size == 0) {
                mAdapter.setEmptyView(EmptyViewUtil.getEmptyView(Constants.TYPE_ORDER_LIST, binding.rvAddressList, "还没有设置收货地址"))
            }
            mAdapter.setNewData(it)
        })
        viewModel.deleteOrSetDefAddressLD.observe(this, Observer {
            LoadingManager.hideProgress(this)
            reqData()
            if (id == "${delTempAddressId}") {
                //删除确认订单选中的
                EventBusUtils.sendNotify(MessageBus.msgId_delete_confirm_order_select_address)
            }
        })
    }

    fun selectAddressMessBus(addressBean: ReceiveAddressBean): MessageBus {
        val builder = MessageBus.Builder()
        return builder.codeType(MessageBus.msgId_select_address_complete).message(addressBean)
            .build();
    }

    fun reqData() {
        viewModel.requestAddressList()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_back -> {
                finish()
            }
            R.id.tv_add_address -> {//新增地址
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.EDIT_OR_ADD_NEW_ADDRESS)
            }
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_new_add_address_success) {
            //编辑 & 新增  刷新
            reqData()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}